package com.lcf.common.util;

import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;

import java.util.*;
import java.util.stream.Collectors;

public class EasyExcelDemo {

    public static void main(String[] args) {

        String templateFile = ResourceUtil.getResource("excel/easy-excel-template.xlsx").getFile();



        try (ExcelWriter excelWriter = EasyExcel.write("F:/aaa.xlsx").withTemplate(templateFile).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 尝试获取表头
            /*field*/
            List<HashMap<Object, Object>> fieldList = getList().get(0).keySet().stream().map(v -> {
                HashMap<Object, Object> hashMap = new HashMap<>();
                hashMap.put("field", String.format("{.%s}", v));
                return hashMap;
            }).collect(Collectors.toList());
            FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
            excelWriter.fill(fieldList, fillConfig, writeSheet); // 填充表头
        }

        try (ExcelWriter excelWriter = EasyExcel.write("F:/aaa1.xlsx").withTemplate("F:/aaa.xlsx").build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(getList(), writeSheet); // 填充数据
        }

    }

    private static List<Map<String, Object>> getList() {
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();

        for (int i = 0; i < 20; i++) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("name", "ZhangSan");
            hashMap.put("age", new Random().nextInt(100));
            hashMap.put("sex", new Random().nextBoolean() ? "男" : "女");
            dataList.add(hashMap);
        }
        return dataList;
    }


}
